<template>
  <div class="app-container">

    <!--搜索表单-->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form" @submit.native.prevent>
        <el-form-item label="年级或班级名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入年级或班级名称"
            clearable
            size="small"
            @keyup.enter.native="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button size="small" icon="el-icon-refresh-right" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 内容区域 -->
    <div class="content-container">
      <div class="content-header">
        <span class="title">班级列表</span>
        <div class="action-buttons-container">
          <!-- 左侧按钮组 -->
          <div class="action-group">
            <el-button size="small" icon="el-icon-download" @click="downloadClassTemplate" type="info">下载模板</el-button>
            <el-upload
              ref="upload"
              action="/api/file/upload/class"
              :auto-upload="true"
              :show-file-list="false"
              :headers="token"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              accept=".xls,.xlsx"
            >
              <template #trigger>
                <el-button type="success" size="small" icon="el-icon-upload2">开始导入</el-button>
              </template>
            </el-upload>
            <el-button type="warning" size="small" icon="el-icon-download" @click="exportClassData">导出数据</el-button>
          </div>
          <!-- 右侧按钮组 -->
          <div class="action-group">
            <el-button type="primary" size="small" @click="dialogFormVisible = true; clazz={}" icon="el-icon-plus">新增班级</el-button>
            <el-button type="danger" size="small" @click="deleteBatch" icon="el-icon-delete">批量删除</el-button>
          </div>
        </div>
      </div>
      <!--表格-->
      <el-table
        ref="multipleTable"
        highlight-current-row
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" width="100" label="序号" align="center" :index="calculateIndex" />
        <el-table-column prop="grade" label="年级" align="center" />
        <el-table-column prop="name" label="班级名称" align="center" />
        <el-table-column label="创建时间" align="center">
          <template v-slot="scope">
            {{ scope.row.createdAt ? scope.row.createdAt.replace('T', ' ') : '' }}
          </template>
        </el-table-column>
        <el-table-column label="最后更新时间" align="center">
          <template v-slot="scope">
            {{ scope.row.updatedAt ? scope.row.updatedAt.replace('T', ' ') : '' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="selectById(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="deleteById(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--分页工具条-->
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="searchForm.page"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog title="编辑班级信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="clazz" label-width="80px" size="mini">
        <el-form-item label="班级名称">
          <el-input v-model="clazz.name" autocomplete="off" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="年级">
          <el-input v-model="clazz.grade" autocomplete="off" placeholder="请输入年级" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add()">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { page, add, update, deleteById, selectById } from '@/api/classes'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      token: { token: getToken() },
      exporting: false,
      formLabelWidth: '80px',
      dialogFormVisible: false,
      clazz: {
        name: '',
        grade: ''
      },
      tableData: [],
      total: 0,
      searchForm: {
        name: '',
        page: 1,
        pageSize: 5
      },
      multipleSelection: [],
      loading: false
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    // 批量删除
    deleteBatch() {
      if (!this.multipleSelection.length) {
        this.$message.warning('请先选择要删除的班级')
        return
      }
      this.$confirm('确认删除所选班级?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById(this.multipleSelection).then((result) => {
          if (result.data.code === 1) {
            this.$message.success('批量删除成功')
            if (this.tableData.length === this.multipleSelection.length && this.searchForm.page > 1) {
              this.searchForm.page--
            }
            this.init()
          } else {
            this.$message.error(result.data.msg)
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(x => x.id)
    },
    calculateIndex(index) {
      return (this.searchForm.page - 1) * this.searchForm.pageSize + index + 1
    },
    exportClassData() {
      this.exporting = true
      const xhr = new XMLHttpRequest()
      xhr.open('GET', '/api/file/exportExcelClass', true)
      xhr.responseType = 'blob'
      xhr.setRequestHeader('token', getToken())
      xhr.onload = () => {
        if (xhr.status === 200) {
          const url = window.URL.createObjectURL(new Blob([xhr.response]))
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', '班级数据.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)
        } else {
          this.$message.error('导出失败')
        }
        this.exporting = false
      }
      xhr.onerror = () => {
        this.$message.error('导出请求失败')
        this.exporting = false
      }
      xhr.send()
    },
    downloadClassTemplate() {
      const link = document.createElement('a')
      link.href = '/api/file/downloadClass'
      link.setAttribute('download', '班级导入模板.xlsx')
      document.body.appendChild(link)
      link.click()
      link.remove()
    },
    beforeUpload(file) {
      const isValidType = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel'
      if (!isValidType) {
        this.$message.error('只能上传Excel文件!')
      }
      return isValidType
    },
    handleUploadSuccess(response) {
      if (response.code === 1) {
        this.$message.success(response.msg || '导入成功')
        this.init()
      } else {
        this.$message.error(response.msg || '导入失败')
      }
    },
    handleUploadError() {
      this.$message.error('文件上传失败，请重试。')
    },
    init() {
      this.loading = true
      page(this.searchForm).then(res => {
        if (res.data.code === 1) {
          this.tableData = res.data.data.rows
          this.total = res.data.data.total
        } else {
          this.$message.error(res.data.msg)
        }
        this.loading = false
      })
    },
    // 保存班级信息
    add() {
      const operation = this.clazz.id ? update(this.clazz) : add(this.clazz)
      operation.then((result) => {
        if (result.data.code === 1) {
          this.$message.success('保存成功')
          this.dialogFormVisible = false
          this.init()
        } else {
          this.$message.error(result.data.msg)
        }
      })
    },
    selectById(id) {
      selectById(id).then((result) => {
        if (result.data.code === 1) {
          this.clazz = result.data.data
          this.dialogFormVisible = true
        } else {
          this.$message.error(result.data.msg)
        }
      })
    },
    deleteById(id) {
      this.$confirm('确认删除该班级?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById([id]).then((result) => {
          if (result.data.code === 1) {
            this.$message.success('删除成功')
            if (this.tableData.length === 1 && this.searchForm.page > 1) {
              this.searchForm.page--
            }
            this.init()
          } else {
            this.$message.error(result.data.msg)
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleSizeChange(pageSize) {
      this.searchForm.pageSize = pageSize
      this.init()
    },
    handleCurrentChange(page) {
      this.searchForm.page = page
      this.init()
    },
    handleSearch() {
      this.searchForm.page = 1
      this.init()
    },
    resetSearch() {
      this.searchForm.name = ''
      this.handleSearch()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.search-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 20px;
  vertical-align: middle;
}

.content-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  margin-bottom: 20px;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.content-header .title {
  font-size: 16px;
  font-weight: bold;
}

.action-buttons-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-grow: 1;
  margin-left: 20px;
}

.action-group {
  display: flex;
  align-items: center;
}

.action-group > * + * {
  margin-left: 10px;
}

.pagination-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  text-align: right;
}

@media (max-width: 1200px) {
  .content-header {
    flex-direction: column;
    align-items: flex-start;
  }
  .action-buttons-container {
    margin-left: 0;
    margin-top: 15px;
    width: 100%;
  }
}
@media (max-width: 768px) {
  .action-buttons-container, .action-group {
    flex-direction: column;
    align-items: flex-start;
    width: 100%;
  }
  .action-group > * {
    margin-bottom: 10px;
  }
  .action-group > * + * {
    margin-left: 0;
  }
}
</style>

<style>
/* 暗色主题适配：仅在 body.dark-theme 下生效 */
body.dark-theme .app-container,
body.dark-theme .search-container,
body.dark-theme .content-container,
body.dark-theme .pagination-container {
  background-color: #1f1f1f !important;
  color: #fff !important;
}

body.dark-theme .el-table,
body.dark-theme .el-table th,
body.dark-theme .el-table td {
  background-color: #232323 !important;
  color: #fff !important;
}

body.dark-theme .el-table__body tr:hover > td {
  background-color: #2b2b2b !important;
}

body.dark-theme .el-input__inner,
body.dark-theme .el-select .el-input__inner {
  background-color: #232323 !important;
  color: #fff !important;
  border-color: #444 !important;
}

body.dark-theme .el-button--primary {
  background-color: #409eff !important;
  border-color: #409eff !important;
  color: #fff !important;
}
body.dark-theme .el-button--danger {
  background-color: #f56c6c !important;
  border-color: #f56c6c !important;
  color: #fff !important;
}
body.dark-theme .el-button--success {
  background-color: #67c23a !important;
  border-color: #67c23a !important;
  color: #fff !important;
}
body.dark-theme .el-button--info {
  background-color: #909399 !important;
  border-color: #909399 !important;
  color: #fff !important;
}
body.dark-theme .el-button--warning {
  background-color: #e6a23c !important;
  border-color: #e6a23c !important;
  color: #fff !important;
}

body.dark-theme .el-pagination,
body.dark-theme .el-pagination__total,
body.dark-theme .el-pagination__jump,
body.dark-theme .el-pagination__editor,
body.dark-theme .el-pagination__sizes,
body.dark-theme .el-pagination__sizes .el-input__inner {
  background-color: #1f1f1f !important;
  color: #fff !important;
  border-color: #444 !important;
}
</style>
